<template>
  <el-header class="header">
    <div class="logo"><img src="@/assets/logo2.png" /></div>
    <div class="logo-title fontPorscheNextRegular">礼物核销系统</div>
  </el-header>
  <div class="subtitle fontPorscheNextRegular">&nbsp;</div>

  <el-form :model="ruleForm" :rules="rules" ref="validateForm" class="login-ruleForm">
    <el-form-item prop="username">
      <el-input
        :placeholder="'账号'"
        v-model.trim="ruleForm.username"
        class="fontPorscheNextRegular"
        :readonly="inputReadOnly"
        @click="inputReadOnly = false"
      >
        <template #prefix>
          <img src="@/assets/icon/icon_user.svg" />
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        @keyup.enter="handleLogin"
        :placeholder="'密码'"
        type="password"
        class="fontPorscheNextRegular"
        v-model.trim="ruleForm.password"
        :readonly="inputReadOnly"
        @click="inputReadOnly = false"
      >
        <template #prefix>
          <img src="@/assets/icon/icon_lock.svg" />
        </template>
      </el-input>
    </el-form-item>
    <!-- <el-form-item prop="verifyCode">
      <div class="verify-code">
        <el-input
          @keyup.enter="handleLogin"
          class="fontPorscheNextRegular"
          :placeholder="t('login.verifyCode')"
          v-model="ruleForm.verifyCode"
        >
          <template #prefix>
            <svg-icon name="verifyCode" size="22px" />
          </template>
        </el-input>
        <div class="code-img"><img :src="checkCodeRef" class="code" @click="checkCode()" /></div>
      </div>
    </el-form-item> -->
    <el-form-item class="operate">
      <div class="login-check">
        <label>
          <img v-if="checkedPwd" src="@/assets/icon/login_check_active.svg" />
          <img v-if="!checkedPwd" src="@/assets/icon/login_check_unactive.svg" />
          记住密码
          <el-checkbox v-show="false" v-model="checkedPwd"> </el-checkbox>
        </label>
      </div>
    </el-form-item>
    <el-form-item>
      <el-button
        type="primary"
        :disabled="!loginAble"
        :loading="loading"
        class="login-btn"
        @click="handleLogin"
        >登录</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script setup>
  import { useStore } from 'vuex';
  import { useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import { login } from '@/api/common/index';
  import { Storage } from '@/utils/index';

  const ruleForm = reactive({
    username: '',
    password: '',
    verifyCode: '',
  });
  const inputReadOnly = ref(true);
  const loginAble = computed(() => {
    return ruleForm.username && ruleForm.password;
  });

  const store = useStore();
  const router = useRouter();

  const validateForm = ref(null);
  const loading = ref(false);
  const checkedPwd = ref(false);
  const redirect = ref('');

  const rules = reactive({
    username: [{ required: true, message: '请输入你的账号', trigger: 'blur' }],
    password: [{ required: true, message: '请输入你的密码', trigger: 'blur' }],
  });

  const checkRemberPwd = (val) => {
    if (val) {
      Storage.setLoc({
        key: 'username',
        value: ruleForm.username,
      });
      Storage.setLoc({
        key: 'password',
        value: ruleForm.password,
      });
      Storage.setLoc({
        key: 'rememberPwd',
        value: true,
      });
    } else {
      Storage.removeLoc('username');
      Storage.removeLoc('password');
      Storage.removeLoc('rememberPwd');
    }
  };
  //清理缓存信息
  const clearInfo = () => {
    [
      'storeId',
      'userInfo',
      'roleItemId',
      'permList',
      'faqImportResult',
      'knowledgeImportResult',
    ].forEach((item) => {
      Storage.setLoc({
        key: item,
        value: '',
      });
    });
  };

  const handleLogin = async () => {
    // clearInfo();
    checkRemberPwd(checkedPwd.value);
    const form = unref(validateForm);
    if (!form) return;

    await form.validate(async (valid) => {
      if (valid) {
        loading.value = true;
        try {
          const res = await login(
            {
              username: ruleForm.username,
              password: ruleForm.password,
            },
            ruleForm.verifyCode
          );
          loading.value = false;

          if (res.data && res.data.token) {
            const fullInfo = res.data;
            const { token } = res.data;
            await store.dispatch('user/setUserInfo', res.data);
            await store.dispatch('user/setAccessToken', token);
            await store.dispatch('routes/setRouteFlag', false);
            await store.dispatch('routes/clearRoutes');
            // 走了home从路由里拿了第一个默认页面
            router.push({
              path: '/prize',
            });
          } else {
            ElMessage.error(res.msg || '登录接口异常');
          }
        } catch (err) {
          loading.value = false;
          console.error(err);
        }
      }
    });
  };

  watch(
    () => router.currentRoute,
    ({ _value }) => {
      // 走了home从路由里拿了第一个默认页面
      const route = _value;
      redirect.value = (route.query && route.query.redirect) || '/';
    },
    {
      immediate: true,
    }
  );

  const fillForm = () => {
    const rememberPwd = Storage.getLoc('rememberPwd');
    if (rememberPwd) {
      checkedPwd.value = true;
      ruleForm.username = Storage.getLoc('username');
      ruleForm.password = Storage.getLoc('password');
    } else {
      checkedPwd.value = false;
      ruleForm.username = '';
      ruleForm.password = '';
    }
  };

  onMounted(async () => {
    fillForm();
  });
</script>
<style lang="scss" scoped>
  .header {
    display: flex;
    align-items: center;
    .logo {
      width: 50px;
      img {
        width: 100%;
      }
    }
    .logo-title {
      margin-left: 12px;
      font-size: 16px;
      font-weight: 600;
    }
  }
  .subtitle {
    margin-top: 48px;
    color: #6b6d70;
  }
  .login-tip {
    margin-top: 24px;
    margin-bottom: 40px;
    font-size: 24px;
    font-weight: 600;
  }
  .subtitle {
    margin-top: 48px;
    color: #6b6d70;
  }
  .login-tip {
    margin-top: 24px;
    margin-bottom: 40px;
    font-size: 24px;
    font-weight: 600;
  }
  .login-ruleForm {
    margin-top: 1rem;

    :deep(.el-input__inner) {
      height: 24px;
      box-shadow: inset 0 0 0 1000px #fff !important;
      font-family: 'PorscheNextRegular', 'Arial Narrow', Arial, 'Heiti SC', 'SimHei', 'sans-serif' !important;
    }
    :deep(.el-input__prefix) {
      top: 2px;
      padding: 0 4px;
    }
    .verify-code {
      display: flex;
      width: 100%;
    }
    .el-input {
      height: 48px !important;
    }
    .code-img {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 150px;
      height: 42px;
      margin-left: 8px;
      padding: 2px 3px 2px 3px;
      border-radius: 2px;
      border: 1px solid #d8d8db;
      img {
        width: 100%;
      }
    }
    .login-btn {
      width: 100%;
      padding: 24px 0;
      border-radius: 2px;
      &.disableBtn {
        background: #ccc !important;
      }
    }
    .login-check {
      flex: 1;
      height: 44px;
      display: flex;
      line-height: 1;
      align-items: center;

      & > label {
        position: relative;
        padding-left: 22px;
        cursor: pointer;
        color: #1d2129;
        font-size: 14px;
        font-style: normal;
        font-weight: 400;
        line-height: 140%; /* 19.6px */
        img {
          width: 14px;
          height: 14px;
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
        }
      }

      .login-btn {
        width: 100%;
        padding: 24px 0;
        border-radius: 2px;
      }
    }
    .operate {
      display: flex;
      margin-top: -2px;
      .forgot_password {
        color: #2762ec;
        font-size: 14px;
        font-style: normal;
        font-weight: 400;
        line-height: 140%; /* 19.6px */
        text-decoration: none;
      }
    }
  }
</style>
